import 'dart:async';
import 'dart:core';
import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_confirm_cancel_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_red_num_widget/common_red_num_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_web_page/common_web_page.dart';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/bean/user_response_bean.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/company/company_detail/event/refresh_company_detail_page_event.dart';
import 'package:e_reception_flutter/ui/create_user/edit_user/edit_user_page.dart';
import 'package:e_reception_flutter/ui/mypage/app_settings_page.dart';
import 'package:e_reception_flutter/ui/mypage/mypage_attendance_ecord_widget/detailed_bean/mypage_proposal_total_bean.dart';
import 'package:e_reception_flutter/ui/punch_in_rule/event/refresh_rule_list_event.dart';
import 'package:e_reception_flutter/ui/punch_in_rule/punch_in_rlue_main_page.dart';
import 'package:e_reception_flutter/ui/test_function/test_function_view_model.dart';
import 'package:e_reception_flutter/ui/test_function/test_history_page.dart';
import 'package:e_reception_flutter/ui/test_function/test_scan_id_page.dart';
import 'package:e_reception_flutter/ui/test_function/test_scan_hsn_page.dart';
import 'package:e_reception_flutter/utils/app_monitoring_class.dart';
import 'package:e_reception_flutter/utils/app_overall_distinguish.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_global_const.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/utils/vg_role_utils.dart';
import 'package:e_reception_flutter/utils/vg_string_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_upgrade/vg_net_delegate.dart';
import 'package:e_reception_flutter/vg_widgets/vg_upgrade/vg_windows_delegate.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:package_info/package_info.dart';
import 'package:upgrade_flutter/upgrade_flutter.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';

import '../app_main.dart';
import 'my_page_view_model.dart';
import 'mypage_attendance_ecord_widget/detailed_bean/mypage_proposal_bean.dart';
import 'mypage_attendance_ecord_widget/feedback_details_page.dart';
import 'mypage_attendance_ecord_widget/mypage_attendance_ecord_widget.dart';
import 'mypage_attendance_ecord_widget/mypage_proposal_improvement.dart';

class Mypage extends StatefulWidget {
  @override
  _MypageState createState() => _MypageState();
}

class _MypageState extends BaseState<Mypage> {
  UserDataBean _user;

  String versionName;

  String get fid => null;

  MyPageViewModel viewModel;
  TestFunctionViewModel testViewModel;

  // List<RecordsImprovementListBean> improvementListData;

  StreamSubscription _submitProposalStreamSubscription;

  AllAndUnReadCntNumber allAndUnReadCnt;

  @override
  void initState() {
    super.initState();
    viewModel = MyPageViewModel(this);
    testViewModel = TestFunctionViewModel(this);
    viewModel.getPunchInRuleCnt();
    VgEventBus.global.streamController.stream.listen((event) {
      // viewModel.getPunchInRuleCnt();
      if (event is RefreshCompanyDetailPageEvent ||
          event is ChangeCompanyEvent||event is RefreshRuleListEvent) {
        print('我的页面:${event?.toString()}');
        viewModel.getPunchInRuleCnt();
      }
    });
    _submitProposalStreamSubscription =
        VgEventBus.global.on<SubmitProposalInterfaceEventMonitor>()?.listen((event) {
          // viewModel?.getSuggestionListData();
          viewModel?.getSuggestionTotal();
        });
    viewModel?.recordsImprovementTotal?.addListener(() {
      allAndUnReadCnt = viewModel?.recordsImprovementTotal?.value;
      setState(() { });
    });
    viewModel?.getSuggestionTotal();
    _getPackageInfo();
  }

  @override
  void dispose() {
    _submitProposalStreamSubscription?.cancel();
    viewModel?.recordsImprovementTotal?.removeListener(() { });
    super.dispose();
  }

  void _getPackageInfo() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    versionName = packageInfo?.version;
  }

  @override
  void didChangeDependencies() {
    _user = UserRepository.getInstance().of(context);
    super.didChangeDependencies();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
      body: Column(
        children: <Widget>[
          GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: () {
              if(!AppOverallDistinguish.comefromAiOrWeStudy()){return;}
              EditUserPage.navigatorPush(
                  context, _user?.comUser?.fuid ?? "", fid);
            },
            child: Container(
              color: ThemeRepository.getInstance().getCardBgColor_21263C(),
              padding: EdgeInsets.only(
                top: 20 + ScreenUtils.getStatusBarH(context),
                bottom: 20,
                left: 15,
              ),
              child: Row(
                children: <Widget>[
                  ClipRRect(
                    borderRadius: BorderRadius.circular(32),
                    child: Container(
                      width: 64,
                      height: 64,
                      decoration: BoxDecoration(shape: BoxShape.circle),
                      child: VgCacheNetWorkImage(
                        showOriginEmptyStr(_user?.comUser?.putpicurl) ??
                            (_user?.comUser?.napicurl ?? ""),
                        defaultErrorType: ImageErrorType.head,
                        defaultPlaceType: ImagePlaceType.head,
                      ),
                    ),
                  ),
                  SizedBox(
                    width: 10,
                  ),
                  Expanded(
                    child: Container(
                      child: Column(
                        children: <Widget>[
                          Row(
                            children: <Widget>[
                              Text(
                                VgStringUtils.subStringAndAppendSymbol(
                                    _user?.comUser?.name , 12,
                                    symbol: "...") ?? "",
                                style: new TextStyle(
                                  color: Color(0xFFD0E0F7),
                                  fontSize: 20,
                                ),
                              ),
                              SizedBox(
                                width: 6,
                              ),
                              Text(
                                _user?.comUser?.nick ?? "",
                                style: new TextStyle(
                                    color: Color(0xFF808388), fontSize: 12),
                              ),
                            ],
                          ),
                          Row(
                            children: <Widget>[
                              Text(
                                _user?.comUser?.phone ?? "",
                                style: new TextStyle(
                                    color: Color(0xFF808388), fontSize: 12),
                              ),
                            ],
                          ),
                          Row(
                            children: <Widget>[
                              Text(
                                VgRoleUtils.isSuperAdmin(_user?.comUser?.roleid)
                                    ? "超级管理员"
                                    : "普通管理员",
                                style: new TextStyle(
                                    color: Color(0xFF808388), fontSize: 12),
                              )
                            ],
                          )
                        ],
                      ),
                    ),
                  ),
                  Opacity(
                    opacity:AppOverallDistinguish.comefromAiOrWeStudy() ? 1:0,
                    child: Padding(
                      padding: const EdgeInsets.all(15),
                      child: Icon(
                        Icons.arrow_forward_ios,
                        size: 14,
                        color: VgColors.INPUT_BG_COLOR,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
          Container(
            color: Color(0xFF191E31),
            height: 10,
          ),
          //考勤规则
          _punchInRuleWidget(context),
          //判断是否有打卡记录，如果没有则隐藏
          if ((_user?.comUser?.punchDayCnt ?? 0) != 0)
            _OptionsBox(
              text: "打卡记录",
              onTap: () {
                Navigator.push(context,
                    new MaterialPageRoute(builder: (context) {
                      return new FaceBrushRecordPage(
                        fuid: UserRepository.getInstance().userData?.comUser?.fuid,
                      );
                    }));
              },
              leftWidget: Padding(
                padding: const EdgeInsets.only(right: 15.0),
                child: Image.asset(
                  'images/icon_punchin_record.png',
                  width: 22,
                  height: 22,
                ),
              ),
            ),
          // _OptionsBox(
          //   leftWidget: Padding(
          //     padding: const EdgeInsets.only(right: 15.0),
          //     child: Image.asset(
          //       'images/icon_version.png',
          //       width: 22,
          //       height: 22,
          //     ),
          //   ),
          //   text: "版本号",
          //   subTextWidget: Text(
          //     versionName ?? "",
          //     style: TextStyle(color: VgColors.INPUT_BG_COLOR),
          //   ),
          //   showArrow: false,
          //   onTap: () {
          //     UpgradeRepository.getInstance(
          //         VgNetDelegate.of(true), VgWindowsDelegate.of(),
          //         onUpgradeErrorChanged: (UpgradeError error) {
          //           if(StringUtils.isEmpty(error?.message)){
          //             if(!(error.message.contains("获取升级详情失败"))){
          //               VgToastUtils.toast(AppMain.context, error?.message);
          //             }
          //           }
          //         }).httpCheckUpgrade();
          //   },
          // ),
          // _OptionsBox(
          //   leftWidget: Padding(
          //     padding: const EdgeInsets.only(right: 15.0),
          //     child: Image.asset(
          //       'images/icon_privacy.png',
          //       width: 22,
          //       height: 22,
          //     ),
          //   ),
          //   text: "隐私协议",
          //   onTap: () {
          //     CommonWebPage.navigatorPush(context, PRIVACY_H5, "隐私协议");
          //   },
          // ),
          _OptionsBox(
            leftWidget: Padding(
              padding: const EdgeInsets.only(right: 15.0),
              child: Image.asset(
                'images/proposal.png',
                width: 22,
                height: 22,
              ),
            ),
            rightWidget: _toRedDotWidget(),
            text: "意见反馈",
            onTap: () {
              if((allAndUnReadCnt?.unreadCnt??0) > 0){
                allAndUnReadCnt?.unreadCnt = 0;
                MyPageFeedBackDetailsWidget.navigatorPush(context);
                setState(() {});
              }else{
                MyPageProposalImprovementWidget.navigatorPush(context,allAndUnReadCnt);
              }
            },
          ),
          _OptionsBox(
            leftWidget: Padding(
              padding: const EdgeInsets.only(right: 15.0),
              child: Image.asset(
                'images/app_settings.png',
                width: 22,
                height: 22,
              ),
            ),
            text: "设置",
            onTap: () {
              AppSettingsPage.navigatorPush(context);
            },
          ),
          Container(
            color: Color(0xFF191E31),
            height: 10,
          ),
          _testWidget(),
          Spacer(),
          // Container(
          //   height: 40,
          //   width: 120,
          //   child: RaisedButton(
          //     onPressed: () async {
          //       bool result =
          //       await CommonConfirmCancelDialog.navigatorPushDialog(context,
          //           title: "提示", content: "是否退出登录？");
          //       if (result == null || result == false) {
          //         return;
          //       }
          //       Future.delayed(Duration(milliseconds: 0), () async {
          //         await UserRepository.getInstance().clearUserInfo();
          //         RouterUtils.popUntil(AppMain.context, AppMain.ROUTER,
          //             rootNavigator: false);
          //         VgToastUtils.toast(AppMain.context, "退出成功");
          //       });
          //     },
          //     child: Text(
          //       "退出登录",
          //       style: TextStyle(color: Color(0xFFF95355)),
          //     ),
          //     color: Color(0xFFF95355).withOpacity(0.1),
          //     elevation: 40,
          //     shape: RoundedRectangleBorder(
          //       borderRadius: BorderRadius.circular(22.5),
          //     ),
          //   ),
          // ),
          SizedBox(
            height: NAV_HEIGHT + 39 + ScreenUtils.getStatusBarH(context),
          ),
        ],
      ),
    );
  }


  Widget _testWidget(){
    return Visibility(
      visible: _user?.outFactoryFlg??false,
      child: GestureDetector(
        onTap: (){
          testViewModel.getUnqualifiedCount(context, (count){
            if((count??0) > 0){
              TestHistoryPage.navigatorPush(context);
            }else{
              TestScanHsnPage.navigatorPush(context);
            }
          });
        },
        child: Container(
          height: 50,
          color: ThemeRepository.getInstance().getCardBgColor_21263C(),
          alignment: Alignment.center,
          child: Row(
            children: <Widget>[
              SizedBox(
                width: 15,
              ),
              Padding(
                padding: const EdgeInsets.only(right: 15.0),
                child: Image.asset(
                  'images/icon_test.png',
                  width: 22,
                  height: 22,
                ),
              ),
              Text(
                "出厂检测",
                style: new TextStyle(
                  color: Color(0xFFD0E0F7),
                  fontSize: 15,
                ),
              ),
              SizedBox(
                width: 6,
              ),
              Image.asset(
                'images/icon_test_hint.png',
                width: 24,
                height: 14,
              ),
              Spacer(),
              Icon(
                Icons.arrow_forward_ios,
                size: 14,
                color: VgColors.INPUT_BG_COLOR,
              ),
              SizedBox(
                width: 15,
              )
            ],
          ),
        ),
      ),
    );
  }

  Widget _toRedDotWidget() {
    if((allAndUnReadCnt?.unreadCnt??0) > 0){
      return CommonRedNumWidget(
        allAndUnReadCnt?.unreadCnt??0,
        isShowZero: false,
      );
    }else{
      return Container(
          child:Text(
          (allAndUnReadCnt?.allCnt??0)==0 ?"":"${allAndUnReadCnt?.allCnt??0}",
            style: TextStyle(color: VgColors.INPUT_BG_COLOR),
          )
      );
    }

  }

  ///考勤规则
  ///超管查看【我的】页面，显示【考勤规则】菜单，右侧显示生效的规则数，为0则显示“去设置”；
  Widget _punchInRuleWidget(BuildContext context) {
    return Visibility(
      visible: VgRoleUtils.isSuperAdmin(
          UserRepository.getInstance().getCurrentRoleId()),
      child: Column(
        children: <Widget>[
          _OptionsBox(
            text: "考勤规则",
            subTextWidget: Padding(
              padding: const EdgeInsets.only(right: 8.0),
              child: StreamBuilder<int>(
                  stream: viewModel.punchInCntStreamController.stream,
                  builder: (context, snapshot) {
                    int cnt;
                    if (snapshot.connectionState == ConnectionState.active) {
                      cnt = snapshot.data;
                    }
                    return Text(
                      (cnt ?? 0) == 0 ? '去设置' : '共$cnt条规则',
                      style: TextStyle(
                          color: (cnt ?? 0) == 0
                              ? VgColors.INPUT_BG_COLOR
                              : ThemeRepository.getInstance()
                              .getPrimaryColor_1890FF(),
                          fontSize: 12,
                          height: 1),
                    );
                  }),
            ),
            onTap: () {
              PunchInRuleMainPage.navigatorPush(context);
            },
            leftWidget: Padding(
              padding: const EdgeInsets.only(right: 15.0),
              child: Image.asset(
                'images/kqgz.png',
                width: 22,
                height: 22,
              ),
            ),
          ),
          Container(
            color: Color(0xFF191E31),
            height: 10,
          ),
        ],
      ),
    );
  }
}

class _OptionsBox extends StatelessWidget {
  final String text;

  final Widget leftWidget;
  final Widget rightWidget;
  final Widget subTextWidget;

  final Function() onTap;

  final bool showArrow;

  const _OptionsBox(
      {Key key,
        this.text,
        this.leftWidget,
        this.onTap,
        this.rightWidget,
        this.subTextWidget,
        this.showArrow = true})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        height: 50,
        color: ThemeRepository.getInstance().getCardBgColor_21263C(),
        alignment: Alignment.center,
        child: Row(
          children: <Widget>[
            SizedBox(
              width: 15,
            ),
            if (leftWidget != null) leftWidget,
            Text(
              text ?? "",
              style: new TextStyle(
                color: Color(0xFFD0E0F7),
                fontSize: 15,
              ),
            ),
            Spacer(),
            if (rightWidget != null) rightWidget,
            SizedBox(width: 9,),
            // leftWidget ?? Container(),
            if (subTextWidget != null) subTextWidget,
            Visibility(
              visible: showArrow,
              child: Icon(
                Icons.arrow_forward_ios,
                size: 14,
                color: VgColors.INPUT_BG_COLOR,
              ),
            ),
            SizedBox(
              width: 15,
            )
          ],
        ),
      ),
    );
  }
}
